package com.example.websocket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 开启Spring Security的功能
 *
 * @author shiwen
 * @date 2020/7/28
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 设置SpringSecurity对 / 和 /login 路径不进行拦截
        http.authorizeRequests()
                .mvcMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 设置SpringSecurityd的登录页面访问路径为 /login
                .loginPage("/login")
                // 登录成功后转向 /chat 路径
                .defaultSuccessUrl("/chat")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            // 在内存中分配两个用户nasus和yangshiwen，用户名和密码一致
            // BCryptPasswordEncoder()是SpringSecurity5.0中新增的加密方式
            // 登录时用BCrypt加密方式对用户密码进行处理
            .passwordEncoder(new BCryptPasswordEncoder())
            .withUser("nasus")
            // 保证用户登录时使用 bcrypt 对密码进行处理再与内存中的密码进行对比
            .password(new BCryptPasswordEncoder().encode("nasus")).roles("USER")
            .and()
            // 登录时用 BCrypt 加密方式对用户密码进行处理
            .passwordEncoder(new BCryptPasswordEncoder())
            .withUser("yangshiwen")
            // 保证用户登录时使用 bcrypt 对密码进行处理再与内存中的密码进行对比
            .password(new BCryptPasswordEncoder().encode("yangshiwen")).roles("USER");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // /resource/static 目录下的静态资源, Spring Security不进行拦截操作
        web.ignoring().antMatchers("/resource/static/**");
    }

}